package com.thirtydays.frame.base.http.okhttp

import com.thirtydays.frame.data.DataManager
import com.thirtydays.frame.util.ext.isNotNullAndNotEmpty
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Response
import java.util.concurrent.TimeUnit

/**
 * @创建者：小垚
 * @时间：2021/7/2212:22
 * @描述：
 */
class OkHttpManager {
    companion object {
        private var builder: OkHttpClient? = null
            get() {
                if (field == null) {
                    field = OkHttpClient.Builder()
                        .addInterceptor(HeadInterceptor())
                        .addInterceptor(LoggerInterceptor())
                        .connectTimeout(10L, TimeUnit.SECONDS)
                        .readTimeout(10L, TimeUnit.SECONDS)
                        .build()
                }
                return field
            }

        fun get(): OkHttpClient {
            return builder!!
        }
    }


    class HeadInterceptor : Interceptor {
        override fun intercept(chain: Interceptor.Chain): Response {
            val url = chain.request().url.newBuilder()
            val newBuilder = chain.request().newBuilder()
            newBuilder.addHeader("Content-Type", "application/json")
            if (DataManager.token.isNotNullAndNotEmpty()) {
                newBuilder.addHeader("accessToken", DataManager.token)
            }
            newBuilder.url(url.build())
            return chain.proceed(newBuilder.build())
        }
    }
}